package com.gitee.melin.bee.core.fs.impl;

import com.gitee.melin.bee.core.fs.FTPProtocol;
import com.gitee.melin.bee.core.fs.FileSystem;
import com.gitee.melin.bee.core.fs.FsConnectionInfo;
import java.util.List;
import net.schmizz.sshj.SSHClient;
import net.schmizz.sshj.transport.verification.PromiscuousVerifier;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.net.ftp.FTPClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class FtpFileSystem implements FileSystem {
    private static final Logger LOGGER = LoggerFactory.getLogger(FtpFileSystem.class);

    @Override
    public boolean bucketExist(FsConnectionInfo connectionInfo) {
        throw new UnsupportedOperationException();
    }

    @Override
    public void testConnection(FsConnectionInfo connectionInfo) {
        try {
            if (FTPProtocol.FTP == connectionInfo.getProtocol()) {
                FTPClient ftpClient = new FTPClient();
                ftpClient.connect(connectionInfo.getHost(), connectionInfo.getPort());
                boolean login = ftpClient.login(connectionInfo.getUser(), connectionInfo.getPassword());
                if (!login) {
                    throw new RuntimeException("Login 失败，请确认账号或者密码是否正确");
                }
            } else if (FTPProtocol.SFTP == connectionInfo.getProtocol()) {
                SSHClient client = new SSHClient();
                client.addHostKeyVerifier(new PromiscuousVerifier());
                client.connect(connectionInfo.getHost(), connectionInfo.getPort());

                if (StringUtils.isNotBlank(connectionInfo.getPassword())) {
                    client.authPassword(connectionInfo.getUser(), connectionInfo.getPassword());
                } else if (StringUtils.isNotBlank(connectionInfo.getSshKeyFile())) {
                    client.authPublickey(connectionInfo.getUser(), connectionInfo.getSshKeyFile());
                } else {
                    throw new RuntimeException("password or sshkey file is blank");
                }
                client.close();

            } else {
                throw new RuntimeException("ftp protocol can not null");
            }
        } catch (Exception e) {
            throw new RuntimeException("ftp test connection error: " + e.getMessage(), e);
        }
    }

    @Override
    public List<String> queryBuckets(FsConnectionInfo connectionInfo) {
        throw new UnsupportedOperationException("Ftp not support queryBuckets");
    }
}
